// pages/orderdetail/orderdetail.js
const app = getApp() // 引入app
const _request = require("../../utils/request.js"); // 引入require;
import {
  getTime,
  regMobile,
  toDecimal2
} from '../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopimgUrl: app.globalData.shopimgUrl,
    orderStatus: "",
    lastbuttonflag: false,
    lastbutton: "",
    refundflag: false,
    orderDetail: {},
    ordertimeStr: "",
    canceltimeStr: "",
    refundtimeStr: "",
    paytimeStr: '',
    stylistNexus: "",
    orderId: "",
    showoverlay: false,
    orderservices: "",
    clock:""
  },

  // 显示电话
  onMobile(e) {
    this.setData({
      showoverlay: true
    })
  },

  // 拨打电话
  goMobile() {
    wx.makePhoneCall({
      phoneNumber: this.data.orderDetail.stylistMobile
    })
  },


  // 隐藏电话
  onClickHide() {
    this.setData({
      showoverlay: false
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let orderStatus = options.orderStatus
    let orderId = options.orderId
    this.setData({
      orderStatus: orderStatus,
      orderId: orderId
    })
    console.log(orderStatus)
    if ("已完成" == orderStatus) {
      this.setData({
        lastbutton: "查看评价",
      })
      this.getOrderComment(orderId);
    } else if ("待接单" == orderStatus) {
      this.setData({
        lastbutton: options.orderBtn,
        lastbuttonflag: true
      })
    }
    this.queryOrderDetail(orderId);
  },

  // 获取评价
  getOrderComment(orderId) {
    _request.get('/storeComment/getOrderComment', {
      orderId: orderId
    }).then((res) => {
      if (res.data.data) {
        this.setData({
          lastbuttonflag: true
        })
      } else {
        this.setData({
          lastbuttonflag: false
        })
      }
    }).catch((error) => {
      console.log(error, 'error');
      this.setData({
        lastbuttonflag: false
      })
    })
  },

  queryOrderDetail(orderId) {
    _request.get('/order/getOrder', {
      orderId: orderId
    }).then((res) => {
      if (res.data.data != null) {

        let data = res.data.data || {}
        data.payamount = (data.payamount || 0).toFixed(2)
        data.orderamount = (data.orderamount || 0).toFixed(2)
        data.newUserMobile = data.userMobile != null ? regMobile(data.userMobile) : ''
        if (data.orderRefund) {
          data.orderRefund.handlingfee = (data.orderRefund.handlingfee || 0).toFixed(2)
          data.orderRefund.refundamount = (data.orderRefund.refundamount || 0).toFixed(2)
        }
        var orderservices = "";
        if (data.option) {
          for (var index in data.option) {
            orderservices = orderservices + data.option[index].serviceName + "￥" + data.option[index].price + " | ";
          }
        }
        if (res.data.data.pendingTime != null) {
          var sDataTime = res.data.data.pendingTime; //获取订单失效的时间戳
          var nowTime = (new Date()).getTime(); //获取系统当前时间戳
          var _time = (sDataTime * 1000) - nowTime //下单以后剩余的时间
          this.count_down(_time);
        }
        orderservices = orderservices.slice(0, orderservices.length - 3);
        this.setData({
          orderDetail: data,
          ordertimeStr: this.getYMDHMS(res.data.data.ordertime),
          createtimeStr: this.getYMDHMS(res.data.data.createtime),
          paytimeStr: this.getYMDHMS(res.data.data.paytime),
          endtimeStr: this.getYMDHMS(res.data.data.endtime),
          canceltimeStr: this.getYMDHMS(res.data.data.canceltime),
          refundtimeStr: this.getYMDHMS(res.data.data.refundtime), 
          stylistNexus: res.data.data.nexus == 0 ? "平台" : "店内",
          orderservices: orderservices
        })
        console.log(this.data.orderDetail)
      }
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  /* 分秒倒计时 */
  count_down(_time) {
    if (_time > 0) { //订单未失效
      this.setData({
        clock: this.date_format(_time), // 渲染倒计时时钟
      });
    }
    let that = this;
    setTimeout(function () { // 倒计时效果
      _time -= 1000;
      that.count_down(_time);
    }, 1000)
  },

  date_format(micro_second) {
    var second = Math.floor(micro_second / 1000); // 秒数
    var hr = Math.floor(second / 3600); // 小时位
    var min = this.fill_zero_prefix(Math.floor((second - hr * 3600) / 60)); // 分钟位
    var sec = this.fill_zero_prefix((second - hr * 3600 - min * 60)); // 秒位
    return min + ":" + sec;
  },

  // 位数不足补零
  fill_zero_prefix(num) {
    return num < 10 ? "0" + num : num
  },

  // 点击查看评价，或者接单按钮
  chooseOption() {
    if ("已完成" == this.data.orderStatus) {
      wx.navigateTo({
        url: '/pages/commentdetail/commentdetail?orderId=' + this.data.orderId
      })
    } else if ("接单" == this.data.orderStatus || "提醒接单" == this.data.orderStatus) {
      console.log('该接单了');
      _request.postObj('/stylistOrder/acceptOrder', {
        orderId: this.data.orderId
      }).then((res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '接单成功',
            icon: 'success',
            duration: 2000
          })
          this.onLoad();
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'error',
            duration: 2000
          })
        }
      })
    }

  },

  getYMDHMS(timestamp) {
    if (!timestamp) {
      return "";
    }
    let time = new Date(timestamp)
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let date = time.getDate()
    let hours = time.getHours()
    let minute = time.getMinutes()
    let second = time.getSeconds()

    if (month < 10) {
      month = '0' + month
    }
    if (date < 10) {
      date = '0' + date
    }
    if (hours < 10) {
      hours = '0' + hours
    }
    if (minute < 10) {
      minute = '0' + minute
    }
    if (second < 10) {
      second = '0' + second
    }
    return year + '-' + month + '-' + date + ' ' + hours + ':' + minute
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    wx.setNavigationBarTitle({
      title: this.data.orderStatus
    })
  },

  gotoWysm() {
    wx.navigateTo({
      url: '/pages/orderdetail/wysm',
    })
  }
})